/* 
 * Copyright 2014 ShangDao.Ltd  All rights reserved.
 * SiChuan ShangDao.Ltd PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 * 
 * @ActCardDetail.java  2014-9-10 上午10:36:08 - Carson
 * @author Guzhu
 * @email:muyi126@163.com
 * @version 1.0
 */

package com.android.tiango.baba.act;

import java.io.File;
import java.io.FileInputStream;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.text.Spannable;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TextView.BufferType;

import com.alibaba.fastjson.JSON;
import com.android.scsd.tiango.R;
import com.android.support.httpclient.HttpCallBack;
import com.android.support.httpclient.HttpClientAsync;
import com.android.support.httpclient.HttpParams;
import com.android.tiango.baba.BaListActivity;
import com.android.tiango.baba.adapter.CardDetailAdapter;
import com.android.tiango.baba.adapter.ExpressionAdapter;
import com.android.tiango.baba.adapter.ExpressionPagerAdapter;
import com.android.tiango.baba.cookie.HttpUrl;
import com.android.tiango.baba.cookie.ShareCookie;
import com.android.tiango.baba.entity.BaseDataEntity;
import com.android.tiango.baba.entity.BaseEntity;
import com.android.tiango.baba.entity.ReplyEntity;
import com.android.tiango.baba.entity.ReplyModel;
import com.android.tiango.baba.entity.SimpleUserModel;
import com.android.tiango.baba.entity.TopicEntity;
import com.android.tiango.baba.entity.TopicModel;
import com.android.tiango.baba.util.Constants;
import com.android.tiango.baba.util.DensityUtil;
import com.android.tiango.baba.util.SmileUtils;
import com.android.tiango.baba.util.StringUtils;
import com.android.tiango.baba.util.TimeToUtil;
import com.android.tiango.baba.util.ToastUtils;
import com.android.tiango.baba.view.MeasureGridView;
import com.android.tiango.baba.view.Paging;
import com.android.tiango.baba.view.Paging.PageChoseListener;
import com.android.tiango.baba.view.PullListView.PullListViewListener;
import com.android.tiango.baba.view.RoundImageView;
import com.android.tiango.baba.view.SharePopWindow;
import com.android.tiango.baba.view.SharePopWindow.ShareInterface;
import com.nineoldandroids.util.StringUtil;

/**
 * 帖子详情
 * @author YW_pc
 * 
 */
public class ActCardDetail extends BaListActivity<ReplyModel> implements
		com.android.tiango.baba.BaListActivity.AddHeaderViewCallBack, PullListViewListener,
		ShareInterface, PageChoseListener {
	private List<String> reslist;
	private List<View> faces;
	private SharePopWindow mShareWindow;
	private PopupWindow mPopupWindow;
	private WindowManager.LayoutParams mWL;
	private int mScreenWidth;
	private int mScreenHeight;
	private ImageView mIv_photo;
	private fiterBroadcast broadcast;
	private String barId;
	private String topicId;
	private String barName;
	private View header;
	private boolean isChosePage = false;
	private ArrayList<ReplyModel> replyList = new ArrayList<ReplyModel>();
	private String replyId;
	private String filePath;
	private static final int UPNUM = 3;// 上传的次数
	private String upImage;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		setHeaderView(this);
		super.onCreate(savedInstanceState);
		Intent intent = getIntent();

		if (intent.hasExtra(Constants.BARID)) {
			barId = intent.getStringExtra(Constants.BARID);
		}
		if (intent.hasExtra(Constants.TOPICID)) {
			topicId = intent.getStringExtra(Constants.TOPICID);
		}
		if (intent.hasExtra(Constants.BARNAME)) {
			barName = intent.getStringExtra(Constants.BARNAME);
		}
		showEmptyView();
		if (null != mTitleBar) {
			mTitleBar.setTitle("帖子详情");
			mTitleBar.setImageBackGround(R.drawable.bg_title_blue);
			mTitleBar.setBackIcon(R.drawable.icon_back);
			mTitleBar.setMoreIcon(R.drawable.icon_share);
			mTitleBar.setMoreLeftIcon(R.drawable.icon_collect);
			mTitleBar.setMoreImageOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					mShareWindow = new SharePopWindow(ActCardDetail.this);
					mShareWindow.setShareInterface(ActCardDetail.this);
					mShareWindow.show();
				}
			});
		}
		setBackOnClickListener();
		mListView.setDivider(null);
		mListView.setPullListener(this);
		mListView.startOnRefresh();
		broadcast = new fiterBroadcast();
		IntentFilter i = new IntentFilter("com.tiangou.aaaa");
		registerReceiver(broadcast, i);
		if (StringUtils.isEmpty(barName)) {
			iv_chihuoba.setVisibility(View.GONE);
		} else {
			iv_chihuoba.setVisibility(View.VISIBLE);
			iv_chihuoba.setText("去" + barName);
		}
		sendReply();
		mListView.setOnScrollListener(new OnScrollListener() {

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				in_buttom.setVisibility(View.GONE);

			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
					int totalItemCount) {

			}
		});
	}

	private void showEmptyView() {
		setEmptyViewMsg("暂时没有帖子哟~");
		emptyListview.setPullListener(this);
	}

	private void initFace() {
		reslist = getExpressionRes(35);// 表情list
		// 初始化表情viewpager
		faces = new ArrayList<View>();
		View gv1 = getGridChildView(1);
		View gv2 = getGridChildView(2);
		faces.add(gv1);
		faces.add(gv2);
	}

	private List<String> getExpressionRes(int getSum) {
		List<String> reslist = new ArrayList<String>();
		for (int x = 1; x <= getSum; x++) {
			String filename = "ee" + x;
			reslist.add(filename);
		}
		return reslist;
	}

	@Override
	protected View getItemView(int position, View convertView, ViewGroup parent) {
		ViewHolder holder;
		if (null == convertView) {
			holder = new ViewHolder();
			convertView = LayoutInflater.from(ActCardDetail.this).inflate(R.layout.item_carddetail,
					null);
			holder.iv_acthead = (RoundImageView) convertView.findViewById(R.id.iv_acthead);
			holder.tv_acttitle = (TextView) convertView.findViewById(R.id.tv_acttitle);
			holder.iv_sex = (ImageView) convertView.findViewById(R.id.iv_sex);
			holder.iv_thelord = (ImageView) convertView.findViewById(R.id.iv_thelord);
			holder.tv_time = (TextView) convertView.findViewById(R.id.tv_time);
			holder.tv_flor = (TextView) convertView.findViewById(R.id.tv_flor);
			holder.tv_actinfo = (TextView) convertView.findViewById(R.id.tv_actinfo);
			holder.ml_gridview = (MeasureGridView) convertView.findViewById(R.id.ml_gridview);

			holder.ll_replycontent = (LinearLayout) convertView.findViewById(R.id.ll_replycontent);
			holder.ll_reply = (LinearLayout) convertView.findViewById(R.id.ll_reply);
			holder.tv_replyname = (TextView) convertView.findViewById(R.id.tv_replyname);
			holder.tv_replycontent = (TextView) convertView.findViewById(R.id.tv_replycontent);
			holder.ml_gridviewreply = (MeasureGridView) convertView
					.findViewById(R.id.ml_gridviewreply);

			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}
		final ReplyModel bean = mListData.get(position);
		initItemView(bean, holder);
		convertView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				in_buttom.setVisibility(View.VISIBLE);
				replyId = bean.getReplyId();
			}
		});
		return convertView;
	}

	class ViewHolder {
		private RoundImageView iv_acthead;
		private TextView tv_acttitle;
		private ImageView iv_sex;
		private ImageView iv_thelord;
		private TextView tv_time;
		private TextView tv_flor;
		private TextView tv_actinfo;
		private MeasureGridView ml_gridview;

		private LinearLayout ll_reply;
		private LinearLayout ll_replycontent;
		private TextView tv_replyname;
		private TextView tv_replycontent;
		private MeasureGridView ml_gridviewreply;

	}

	private void initItemView(ReplyModel bean, ViewHolder holder) {
		if (null != bean) {
			SimpleUserModel userModel = bean.getReplyUser();
			if (null != userModel) {
				mImageLoader.loadImage(userModel.getAvatarUrl(), holder.iv_acthead);
				holder.tv_acttitle.setText(userModel.getNickName());
				if (userModel.getGender() == 1) {
					holder.iv_sex.setBackgroundResource(R.drawable.bg_sex);
				} else if (userModel.getGender() == 2) {
					holder.iv_sex.setBackgroundResource(R.drawable.bg_sex_girl);
				}
			}
			if (bean.getIsBarOwner() == 1)
				holder.iv_thelord.setVisibility(View.VISIBLE);
		} else {
			holder.iv_thelord.setVisibility(View.INVISIBLE);
		}
		if (bean.getIsTopicOwner() == 1) {
			holder.tv_flor.setText("楼主");
			holder.tv_flor.setTextColor(getResources().getColor(R.color.font_blue));
		} else {
			holder.tv_flor.setText(bean.getFloorNo() + "楼");
			holder.tv_flor.setTextColor(getResources().getColor(R.color.color_light));
		}
		holder.tv_time.setText(TimeToUtil.getSystemDayFormat(bean.getCreateTime()));
		String replyContent = bean.getReplyContent();
		if (!StringUtils.isEmpty(replyContent)) {
			Spannable span = SmileUtils.getSmiledText(this, replyContent);
			holder.tv_replycontent.setText(span, BufferType.SPANNABLE);
			holder.tv_actinfo.setText(span);
		} else {
			holder.tv_actinfo.setText(replyContent);
		}

		SimpleUserModel commentUser = bean.getCommentUser();
		if (null == commentUser) {
			holder.ll_reply.setVisibility(View.GONE);
		} else {
			holder.ll_reply.setVisibility(View.VISIBLE);
			Spannable replySpan = SmileUtils.getSmiledText(this, bean.getCommentContent());
			holder.tv_replycontent.setText(replySpan, BufferType.SPANNABLE);
			holder.tv_replyname.setText("回复" + bean.getCommentFloorNo() + "楼 "
					+ commentUser.getNickName());
		}
		String img = bean.getReplyImages();
		if (StringUtils.isEmpty(img)) {
			holder.ml_gridview.setVisibility(View.GONE);
		} else {
			holder.ml_gridview.setVisibility(View.VISIBLE);
			String[] imgs = img.split(",");
			List<String> list = Arrays.asList(imgs);
			CardDetailAdapter cardAdapter = new CardDetailAdapter(ActCardDetail.this);
			cardAdapter.setData(list);
			holder.ml_gridview.setAdapter(cardAdapter);

		}

		holder.ml_gridview.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				Intent intent = new Intent(ActCardDetail.this, ActImgBrowse.class);
				String[] value = {
						"http://a.hiphotos.baidu.com/image/w%3D310/sign=7ca3586037a85edffa8cf822795509d8/bba1cd11728b47107980ccfcc0cec3fdfc032356.jpg",
						"http://e.hiphotos.baidu.com/image/pic/item/aec379310a55b319c7d37aa641a98226cffc173e.jpg",
						"http://img0.bdstatic.com/img/image/shouye/mxlmh-9420812562.jpg",
						"http://img0.bdstatic.com/img/image/shouye/mxtly-11896748157.jpg" };
				intent.putExtra("urls", value);
				startActivity(intent);
			}

		});
	}

	@Override
	public void onPullRefresh() {
		if (!isChosePage) {
			mPageIndex = 1;
		}
		loadData(barId, topicId);

	}

	@Override
	public void onPullLoadMore() {
		if (!isChosePage) {
			mPageIndex += 1;
		}
		loadData(barId, topicId);
	}

	private TextView tv_title;
	private TextView iv_chihuoba;
	private ImageView iv_actre;
	private ImageView iv_jin;
	private ImageView iv_din;

	private ImageView iv_face;
	private EditText et_msg;
	private ImageView iv_next;
	private RelativeLayout in_buttom;

	@Override
	public void addHeaderView() {
		mWL = getWindow().getAttributes();
		header = LayoutInflater.from(this).inflate(R.layout.header_detail, null);
		tv_title = (TextView) header.findViewById(R.id.tv_title);
		iv_actre = (ImageView) header.findViewById(R.id.iv_actre);
		iv_jin = (ImageView) header.findViewById(R.id.iv_jin);
		iv_din = (ImageView) header.findViewById(R.id.iv_din);
		// TextView tv_content = (TextView) header.findViewById(R.id.tv_content);
		iv_chihuoba = (TextView) header.findViewById(R.id.iv_chihuoba);
		mListView.addHeaderView(header);

		// View footer = LayoutInflater.from(this).inflate(R.layout.layout_send_card, null);
		in_buttom = (RelativeLayout) findViewById(R.id.in_buttom);
		in_buttom.setVisibility(View.GONE);
		iv_face = (ImageView) in_buttom.findViewById(R.id.iv_face);
		mIv_photo = (ImageView) in_buttom.findViewById(R.id.iv_photo);
		et_msg = (EditText) in_buttom.findViewById(R.id.et_msg);
		initFace();
		iv_next = (ImageView) in_buttom.findViewById(R.id.iv_next);

		final LinearLayout ll_face_container = (LinearLayout) in_buttom
				.findViewById(R.id.ll_face_container);
		ViewPager vPager = (ViewPager) in_buttom.findViewById(R.id.vPager);
		vPager.setAdapter(new ExpressionPagerAdapter(faces));
		iv_face.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (ll_face_container.getVisibility() == View.GONE) {
					ll_face_container.setVisibility(View.VISIBLE);
				} else {
					ll_face_container.setVisibility(View.GONE);
				}

			}
		});
		mIv_photo.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				getPopupWindowInstance();
				if (null != mPopupWindow) {
					mPopupWindow.showAtLocation(v, Gravity.BOTTOM, 0, 0);
				}
			}
		});
		iv_next.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Paging pad = new Paging(ActCardDetail.this, 10);
				pad.setPageChoseListener(ActCardDetail.this);
				pad.showPaging(v);

			}
		});
		et_msg.setOnFocusChangeListener(new OnFocusChangeListener() {

			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				if (hasFocus) {
					ll_face_container.setVisibility(View.GONE);
				}
			}
		});
	}

	/*
	 * PopupWindow
	 */
	private void getPopupWindowInstance() {
		if (null != mPopupWindow) {
			mPopupWindow.dismiss();
			mPopupWindow = null;
			mWL.alpha = 1;
			getWindow().setAttributes(mWL);
			return;
		} else {
			mWL.alpha = 0.5f; // 0.0-1.0
			getWindow().setAttributes(mWL);
			initPopuptWindow();
		}
	}

	/*
	 * PopupWindow
	 */
	private void initPopuptWindow() {
		mScreenWidth = getWindowManager().getDefaultDisplay().getWidth();
		mScreenHeight = getWindowManager().getDefaultDisplay().getHeight();
		LayoutInflater layoutInflater = LayoutInflater.from(this);
		View popupWindow = layoutInflater.inflate(R.layout.popup_window, null);

		mPopupWindow = new PopupWindow(popupWindow, mScreenWidth - 80,
				DensityUtil.dip2px(this, 200));
		mPopupWindow.setFocusable(true);

		// mPopupWindow.setWindowLayoutMode((mScreenWidth-mPopupWindowWidth)/2, mScreenHeight-mPopupWindowHeight);
		TextView popup_dismiss = (TextView) popupWindow.findViewById(R.id.tv_popup_dismiss);
		TextView popup_load = (TextView) popupWindow.findViewById(R.id.tv_load);
		TextView popup_camera = (TextView) popupWindow.findViewById(R.id.tv_photo);
		popup_dismiss.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				getPopupWindowInstance();
			}
		});
		popup_load.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				getPopupWindowInstance();
				loadPhotos(10);

			}
		});
		popup_camera.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				getPopupWindowInstance();
				showActivity(ActPhotoCamera.class, false);

			}
		});
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, requestCode, data);
		if (requestCode == 10 && data != null && resultCode == Activity.RESULT_OK) {
			Bitmap cameraBitmap = (Bitmap) data.getExtras().get("data");
			Uri uri = data.getData();
			if (null != uri) {
				filePath = DensityUtil.getAbsoluteImagePath(this, uri);
			}
			mIv_photo.setImageBitmap(cameraBitmap);
			// getPopupWindowInstance();
		}
	}

	/**
	 * 本地相册
	 * @param requestCode
	 */
	private void loadPhotos(int requestCode) {
		Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
		intent.addCategory(Intent.CATEGORY_OPENABLE);
		intent.setType("image/*");
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", 80);
		intent.putExtra("outputY", 80);
		intent.putExtra("return-data", true);
		startActivityForResult(intent, requestCode);
	}

	/**
	 * 获取表情的gridview的子view
	 * 
	 * @param i
	 * @return
	 */
	private View getGridChildView(int i) {
		View view = View.inflate(this, R.layout.expression_gridview, null);
		MeasureGridView gv = (MeasureGridView) view.findViewById(R.id.gridview);
		List<String> list = new ArrayList<String>();
		if (i == 1) {
			List<String> list1 = reslist.subList(0, 20);
			list.addAll(list1);
		} else if (i == 2) {
			list.addAll(reslist.subList(20, reslist.size()));
		}
		list.add("delete_expression");
		final ExpressionAdapter expressionAdapter = new ExpressionAdapter(this, list);
		gv.setAdapter(expressionAdapter);
		gv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				String filename = expressionAdapter.getItem(position);
				try {
					if (filename != "delete_expression") { // 不是删除键，显示表情
						// 这里用的反射，所以混淆的时候不要混淆SmileUtils这个类
						Class clz = Class.forName("com.android.tiango.baba.util.SmileUtils");
						Field field = clz.getField(filename);
						et_msg.append(SmileUtils.getSmiledText(ActCardDetail.this,
								(String) field.get(null)));
					} else { // 删除文字或者表情
						if (!TextUtils.isEmpty(et_msg.getText())) {
							et_msg.requestFocus();
							int selectionStart = et_msg.getSelectionStart();// 获取光标的位置
							if (selectionStart > 0) {
								String body = et_msg.getText().toString();
								String tempStr = body.substring(0, selectionStart);
								int i = tempStr.lastIndexOf("[");// 获取最后一个表情的位置
								if (i != -1) {
									CharSequence cs = tempStr.substring(i, selectionStart);
									if (SmileUtils.containsKey(cs.toString()))
										et_msg.getEditableText().delete(i, selectionStart);
									else
										et_msg.getEditableText().delete(selectionStart - 1,
												selectionStart);
								} else {
									et_msg.getEditableText().delete(selectionStart - 1,
											selectionStart);
								}
							}
						}

					}
				} catch (Exception e) {
					e.printStackTrace();
				}

			}
		});
		return view;
	}

	public class fiterBroadcast extends BroadcastReceiver {

		public fiterBroadcast() {
			super();
		}

		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (action.equals("com.tiangou.aaaa")) {
				filePath = intent.getStringExtra("fitername");
				Uri uri = Uri.fromFile(new File(filePath));
				mIv_photo.setImageURI(uri);
			}
		}

	}

	@Override
	public void sinaShare() {// 新浪分享

	}

	@Override
	public void tentShare() {// qq分享

	}

	@Override
	public void wxcircleShare() {// 朋友圈分享

	}

	@Override
	public void tiangouShare() {// 天购分享

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		unregisterReceiver(broadcast);
	}

	@Override
	public void pageChose(int page) {// 分页
		mPageIndex = page;
		isChosePage = true;
		mListView.startOnRefresh();
	}

	/**
	 * 获取帖子详情的信息
	 * @param barId
	 * @param topicId
	 */
	private void loadData(final String barId, final String topicId) {
		HttpClientAsync client = HttpClientAsync.getInstance();
		client.setPrintLog(true);
		HttpParams param = new HttpParams();
		param.put("barId", barId);
		param.put("topicId", topicId);
		param.put("token", ShareCookie.getToken());
		client.get(HttpUrl.getUrl(HttpUrl.TOPICINFO), param, new HttpCallBack() {

			@Override
			public void onHttpSuccess(Object arg0) {
				TopicEntity entity = (TopicEntity) arg0;
				TopicModel bean = entity.getData();
				ReplyModel replyModel = new ReplyModel();
				replyModel.setBarId(bean.getBarId());
				replyModel.setTopicId(bean.getTopicId());
				replyModel.setReplyUser(bean.getSimpleUser());
				replyModel.setCreateTime(bean.getCreateTime());
				replyModel.setReplyImages(bean.getImages());
				replyModel.setReplyContent(bean.getTopicContent());
				replyModel.setIsBarOwner(bean.getIsBarOwner());
				replyModel.setIsTopicOwner(1);
				replyList.clear();
				replyList.add(replyModel);
				if (null != bean) {
					tv_title.setText(bean.getTopicName());
					if (bean.getIsHot() == 1) {// 热帖
						iv_actre.setVisibility(View.VISIBLE);
					} else {
						iv_actre.setVisibility(View.INVISIBLE);
					}
					if (bean.getIsNice() == 1) {// 精华
						iv_jin.setVisibility(View.VISIBLE);
					} else {
						iv_jin.setVisibility(View.INVISIBLE);
					}
					if (bean.getIsTop() == 1) {// 置顶
						iv_din.setVisibility(View.VISIBLE);
					} else {
						iv_din.setVisibility(View.INVISIBLE);
					}
					setCollect(bean.getIsCollected());
					if (StringUtils.isEmpty(bean.getBarId())) {
						mListView.removeHeaderView(header);
					}
				} else {
					mListView.removeHeaderView(header);
				}
				loadReplyList(barId, topicId);
			}

			@Override
			public void onHttpStarted() {

			}

			@Override
			public void onHttpFailure(Exception arg0, String arg1) {
				if (!StringUtils.isEmpty(arg1)) {
					ToastUtils.showMessage(arg1);
				}
			}
		}, TopicEntity.class);//
	}

	/**
	 * 获取回复
	 * @param barId
	 * @param topicId
	 */
	private void loadReplyList(String barId, String topicId) {
		HttpClientAsync client = HttpClientAsync.getInstance();
		client.setPrintLog(true);
		HttpParams param = new HttpParams();
		param.put("barId", barId);
		param.put("topicId", topicId);
		param.put("pageIndex", mPageIndex);
		param.put("pageSize", Constants.PAGE_SIZE);
		client.get(HttpUrl.getUrl(HttpUrl.TOPICREPLIES), param, new HttpCallBack() {

			@Override
			public void onHttpSuccess(Object arg0) {
				ReplyEntity entity = (ReplyEntity) arg0;
				ArrayList<ReplyModel> list = entity.getData();
				ArrayList<ReplyModel> newList = new ArrayList<ReplyModel>();
				if (mPageIndex == 1) {
					newList.addAll(replyList);
					newList.addAll(list);
					if (null != newList) {
						mAdapter.putData(newList);
					}
				} else {
					if (null != list) {
						mAdapter.putData(list);
					}
				}
				mListView.onRefreshFinish();
				mListView.onLoadFinish();
				isChosePage = false;
			}

			@Override
			public void onHttpStarted() {

			}

			@Override
			public void onHttpFailure(Exception arg0, String arg1) {
				isChosePage = false;
				mListView.onRefreshFinish();
				mListView.onLoadFinish();
				if (!StringUtils.isEmpty(arg1)) {
					ToastUtils.showMessage(arg1);
				}
			}
		}, ReplyEntity.class);//
	}

	/**
	 * 添加收藏
	 */
	private void collect() {
		showWaitingDialog();
		HttpClientAsync client = HttpClientAsync.getInstance();
		client.setPrintLog(true);
		HttpParams param = new HttpParams();
		param.put("barId", barId);
		param.put("topicId", topicId);
		param.put("token", ShareCookie.getToken());
		param.put("collectType", "1");
		client.post(HttpUrl.getUrl(HttpUrl.CollectTopic), param, new HttpCallBack() {

			@Override
			public void onHttpSuccess(Object arg0) {
				dismissWaitingDialog();
				BaseEntity entity = (BaseEntity) arg0;
				if (null != entity) {
					// ToastUtils.showMessage(entity.getMessage());
					ToastUtils.showMessage("收藏成功");
					setCollect(entity.getState());
				}
			}

			@Override
			public void onHttpStarted() {

			}

			@Override
			public void onHttpFailure(Exception arg0, String arg1) {
				dismissWaitingDialog();
				if (!StringUtils.isEmpty(arg1)) {
					ToastUtils.showMessage(arg1);
				}
			}
		}, BaseEntity.class);

	}

	private void setCollect(int status) {
		if (status == 1) {
			mTitleBar.setMoreLeftIcon(R.drawable.icon_collected);
			mTitleBar.setMoreImageOnClickListener(null);
		} else {
			mTitleBar.setMoreLeftIcon(R.drawable.icon_collect);
			mTitleBar.setMoreLeftIconListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					collect();
				}
			});
		}
	}

	/**
	 * 回复
	 */
	private void reply(String content) {
		showWaitingDialog();
		HttpClientAsync client = HttpClientAsync.getInstance();
		client.setPrintLog(true);
		HttpParams param = new HttpParams();
		param.put("barId", barId);
		param.put("topicId", topicId);
		param.put("token", ShareCookie.getToken());
		if (!StringUtils.isEmpty(replyId)) {
			param.put("replyId", replyId);// 回复的id 如果回复楼主 就不传该参数
		}
		param.put("location", "");// 位置
		param.put("replyContent", content);
		param.put("replyImages", upImage);// 回复的图片

		client.post(HttpUrl.getUrl(HttpUrl.ReplyOnTheTopic), param, new HttpCallBack() {

			@Override
			public void onHttpSuccess(Object arg0) {
				dismissWaitingDialog();
				BaseEntity entity = (BaseEntity) arg0;
				if (null != entity) {
					// ToastUtils.showMessage(entity.getMessage());
					replyId = "";
					et_msg.setText("");
					ToastUtils.showMessage("回复成功");
					mListView.startOnRefresh();
					mIv_photo.setImageResource(R.drawable.icon_photo);
					in_buttom.setVisibility(View.GONE);
				}

			}

			@Override
			public void onHttpStarted() {

			}

			@Override
			public void onHttpFailure(Exception arg0, String arg1) {
				dismissWaitingDialog();
				if (!StringUtils.isEmpty(arg1)) {
					ToastUtils.showMessage(arg1);
				}
			}
		}, BaseEntity.class);

	}

	private void sendReply() {
		et_msg.setOnEditorActionListener(new TextView.OnEditorActionListener() {
			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				if (!StringUtils.isEmpty(et_msg.getText().toString())) {

					if (actionId == EditorInfo.IME_ACTION_SEND) {
						String msg = et_msg.getText().toString();
						if (StringUtils.isEmpty(msg)) {
							ToastUtils.showMessage("没有输入回复的内容");
						} else {
							if (StringUtils.isEmpty(filePath)) {
								reply(msg);
							} else {
								upPhoto(msg);
							}

							/* 隐藏软键盘 */
							InputMethodManager imm = (InputMethodManager) v.getContext()
									.getSystemService(Context.INPUT_METHOD_SERVICE);
							if (imm.isActive()) {
								imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
							}
						}
						return true;
					}
				} else {
					ToastUtils.showMessage(getStringValue(R.string.info_Reply_not_null));
				}
				return false;
			}
		});
	}

	/**
	 * 上传图片
	 * @param filePath
	 */
	private void upPhoto(String msg) {
		new UploadTask(msg).execute();
	}

	public class UploadTask extends AsyncTask<String, Void, String> {
		private String msg;

		public UploadTask(String msg) {
			this.msg = msg;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			showWaitingDialog();
		}

		@Override
		protected String doInBackground(String... params) {
			String string = "";
			try {
				File file = new File(filePath);
				if (file.exists()) {
					string = upLoadTest(HttpUrl.getUrl(HttpUrl.UploadNormalImage), filePath);
				} else {

				}
			} catch (Exception e) {
				e.printStackTrace();
			}

			return string;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			dismissWaitingDialog();
			if (!StringUtil.isEmpty(result)) {
				try {
					BaseDataEntity entity = (BaseDataEntity) JSON.parseObject(result,
							BaseDataEntity.class);
					if (entity != null) {
						upImage = entity.getData();
						if (!StringUtil.isEmpty(upImage)) {
							filePath = "";
							reply(msg);
						} else {
							ToastUtils.showMessage("上传图片失败");
						}
					} else {
						ToastUtils.showMessage("上传图片失败");
					}
				} catch (Exception e) {
					e.printStackTrace();
					ToastUtils.showMessage("上传图片失败");
				}
			} else {
				ToastUtils.showMessage("上传图片失败");
			}
		}

	}

	private String upLoadTest(String url, String filePath) {
		HttpClient httpclient = new DefaultHttpClient();
		String strResult = "";
		HttpPost httppost = new HttpPost(url);
		File file = new File(filePath);
		MultipartEntityBuilder mBuilder = MultipartEntityBuilder.create(); // 文件传输
		try {
			mBuilder.addBinaryBody("file", new FileInputStream(file),
					ContentType.APPLICATION_OCTET_STREAM, ".jpg");
			mBuilder.addTextBody("token", ShareCookie.getToken());
			httppost.setEntity(mBuilder.build());
			httppost.setHeader("User-Agent", "Tiangou-Android");
			HttpResponse response = httpclient.execute(httppost);
			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode == HttpStatus.SC_OK) {
				strResult = EntityUtils.toString(response.getEntity());
				return strResult;
			} else {
				return strResult;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return strResult;

	}
}
